<template>
  <div>
    <el-card>
      <template #header>
        <h4>管理员信息</h4>
      </template>
      <div class="box">
        <span>管理员ID: {{ info.id }}</span>
        <el-divider></el-divider>
        <span>账号： {{ info.account }}</span>
        <el-divider></el-divider>
        <span>用户组：{{ info.userGroup }} </span>
        <el-divider></el-divider>
        <span>创建时间：{{ info.ctime | formatDate }} </span>
        <el-divider></el-divider>
        <p>
          <span>管理员头像：</span>

          <!-- 上传头像 -->
          <el-upload
            class="avatar-uploader"
            action="http://172.16.100.203:5000/users/avatar_upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </p>
        <el-divider></el-divider>
        <el-button type="primary" @click="uploading">保存头像</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { avataredit } from '../../api/info.js'
import local from '../../utils/local.js'
export default {
  data() {
    return {
      info: {},
      imageUrl: '',
      imgUrl: ''
    }
  },
  created() {
    this.getinfo()
  },
  methods: {
    // 个人信息
    getinfo() {
      const data = JSON.parse(local.get('info'))
      console.log(data)
      this.info = data
    },

    // 修改头像
    async uploading() {
      const data = await avataredit({
        imgUrl: this.imgUrl
      })
      console.log(data)
      if (data.code === 0) {
        // 刷新
        location.reload()
      }
    },

    // 上传头像成功
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.imgUrl = res.imgUrl
    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style lang="less" scoped>
.box {
  p {
    display: flex;
    align-items: center;
  }
}

/deep/.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
